//
//  BeautifulViewController.m
//  Dsgfds
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 胡泉. All rights reserved.
//

#import "BeautifulViewController.h"
#import "BeautifulTableViewCell.h"
#import "PKRequestManager.h"
#import "BeautifulModel.h"
#import "UIImageView+WebCache.h"
#import "BeautifulDetailViewController.h"
#import "MJRefresh.h"
#import "FMDatabase.h"
@interface BeautifulViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) FMDatabase *dataBase;// 数据库
@property (weak, nonatomic) IBOutlet UITableView *contentTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) BOOL isLoad;
@property (nonatomic, assign) NSInteger page;

@end

@implementation BeautifulViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.contentTableView.delegate = self;
    self.contentTableView.dataSource = self;
    self.navigationItem.title = @"美文";
    self.contentTableView.rowHeight = (SCREEN_WIDTH - 20) * 425 / 540 + 10;
    UINib *nib = [UINib nibWithNibName:@"BeautifulTableViewCell" bundle:[NSBundle mainBundle]];
    _contentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contentTableView registerNib:nib forCellReuseIdentifier:@"Bcell"];
    self.dataArray = [NSMutableArray array];
    _isLoad = YES;
    _page = 1;
    [self configureData];
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"HQ.db"];
    // 根据路径打开文件 不存在则创建这个文件
    _dataBase = [FMDatabase databaseWithPath:filePath];
    NSLog(@"%@",filePath);
    // 通过open这个方法打开数据库 打开成功就创建表格
    if ([_dataBase open])
    {
        NSLog(@"杂志数据库打开成功");
        [_dataBase executeUpdate:@"create table magezine (contentid text , imgurl text)"];
        
    }
    else
    {
        NSLog(@"杂志数据库打开失败");
    }
    // 根据查找语句查找表的内容
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"select * from magezine"];
    while ([resultSet next])
    {
        NSString *contentid = [resultSet stringForColumn:@"contentid"];
        NSString *imgurl = [resultSet stringForColumn:@"imgurl"];
        BeautifulModel *model = [[BeautifulModel alloc] init];
        model.imgurl = imgurl;
        model.contentid = contentid;
        [_dataArray addObject:model];
    }
    [resultSet close];
    
    __weak BeautifulViewController  *beauVC = self;
    _contentTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _isLoad = YES;
        _page = 1;
        [beauVC configureData];
    }];
    [_contentTableView.header beginRefreshing];
    
    _contentTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _isLoad = NO;
        _page += 1;
        [beauVC configureData];
    }];
    [_contentTableView.footer beginRefreshing];
    // Do any additional setup after loading the view from its nib.
}

- (void)configureData
{
//    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
//    if (_isLoad)
//    {
//        parDic[@"page"] = @"1";
//    }
//    else{
//    parDic[@"page"] = [NSString stringWithFormat:@"%d",_page];
//    }
    [PKRequestManager PKRequestManagerrequsetWithType:GET URLString:[NSString stringWithFormat:@"http://www.yueduziji.com/a/list/?page_size=10&page=%ld",(long)_page] ParDIc:nil finish:^(NSData *data) {
        [_dataBase executeUpdate:@"delete from magezine"];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        if (_isLoad)
        {
            [_dataArray removeAllObjects];
        }
        for (NSDictionary *inDic in dict[@"data"])
        {
            BeautifulModel *model = [[BeautifulModel alloc] init];
            [model setValuesForKeysWithDictionary:inDic];
            [_dataArray addObject:model];
            [_dataBase executeUpdate:@"insert into magezine (contentid , imgurl) values(?,?)",model.contentid, model.imgurl];
        }
        [self.contentTableView reloadData];
        [_contentTableView.header endRefreshing];
        [_contentTableView.footer endRefreshing];
    } error:^(NSError *error) {
        NSLog(@"error----%@",[error localizedDescription]);
    }];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BeautifulTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Bcell" forIndexPath:indexPath];
    BeautifulModel *model = _dataArray[indexPath.row];
    [cell.contentImageView sd_setImageWithURL:[NSURL URLWithString:model.imgurl]];

    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BeautifulDetailViewController *beauDVC = [[BeautifulDetailViewController alloc] init];
    beauDVC.model = _dataArray[indexPath.row];
    [self.navigationController pushViewController:beauDVC animated:YES];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
